//
//  NECircleProgressView.m
//  NetEasyNews
//
//  Created by weiwang on 16/7/17.
//  Copyright © 2016年 王伟. All rights reserved.
//

#import "NECircularProgressView.h"
#import <QuartzCore/QuartzCore.h>

@implementation NECircularProgressView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self _settings];
    }
    
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self _settings];
    }
    return self;
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    self._shapeLayer.path = self._layoutPath.CGPath;

}

#pragma mark- setter and getter
-(void)setProgress:(CGFloat)progress
{
    [self _updateProgress:progress];
    if (self.progressChangedBlock) {
        self.progressChangedBlock(self, _progress);
    }
    _progress = progress;
}



#pragma mark- event action
-(void)click
{
    if (self.progressChangedBlock) {
        self.progressChangedBlock(self, 0.0);
    }
}

#pragma mark- private function

-(void)_settings
{
    self.progress = 1.f;
    self.alpha = 0.4f;
    self.backgroundColor = [UIColor clearColor];
    
    self._shapeLayer.lineWidth = 2.f;
    self._shapeLayer.strokeColor = [UIColor redColor].CGColor;
    
    UILabel *label = [[UILabel alloc] initWithFrame:self.bounds];
    [self addSubview:label];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    [label setFont:[UIFont systemFontOfSize:15.f]];
    label.text = @"跳过";
    
    UIControl *control = [[UIControl alloc] initWithFrame:self.bounds];
    control.backgroundColor = [UIColor clearColor];
    [control addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:control];
}

+(Class)layerClass
{
    return [CAShapeLayer class];
}

-(CAShapeLayer *)_shapeLayer
{
    return (CAShapeLayer *)(self.layer);
}

-(UIBezierPath *)_layoutPath
{
    const double TWO_M_PI = 2.0 * M_PI;
    const double startAngle = 0.75 * TWO_M_PI;
    const double endAngle = startAngle - TWO_M_PI;
    
    CGFloat width = self.frame.size.width;
    return [UIBezierPath bezierPathWithArcCenter:CGPointMake(width/2.0f, width/2.0f)
                                          radius:self.frame.size.width/2.0f
                                      startAngle:startAngle
                                        endAngle:endAngle
                                       clockwise:NO];
}

-(void)_updateProgress:(CGFloat)progress
{
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
    self._shapeLayer.strokeEnd = progress;
    [CATransaction commit];
}
@end
